package plugin;

import Main.Parameters;
import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.jar.Attributes;
import system.MessageOUTPUT;

/**
 * Plugin service
 * @author ZeM
 */
public class Plugin {

    /**
     * Check plugin to exist
     * @param plugin_name name of plagin: name.jar
     * @return true if everything is OK
     */
    public boolean Exists(String plugin_name) {
        File plugin_folder=new File(Parameters.PluginDirectory+plugin_name);
       if(plugin_folder.exists()){
           File plugin_jar=new File(Parameters.PluginDirectory+plugin_name+File.separatorChar+plugin_name+".jar");
           if(plugin_jar.exists()){
                return true;

           }else {
           //plugin folder exists but plugin is missed
            String[] mes = {plugin_name};
            new MessageOUTPUT().OUTPUT("er0022",mes);
               return false;
           }

       }else
       {
       //can't find plugin
             String[] mes = {plugin_name};
            new MessageOUTPUT().OUTPUT("er0008",mes);
            return false;
       }



    }
    /**
     * Null all plugin parameters
     */
    public void NullParameters() {
    Parameters.Plugin_parameter_name=null;
    Parameters.Plugin_group_parameter_name=null;
    Parameters.Plugin_group_name=null;

    }
    
    

    /**
     * Getting main class of jar file. Main class must be mentioned in manifest.
     * @param jarURL The URL adress of jar
     * @return main class name or null if not found
     */
    public String GetMainClass(URL jarURL) {
        String p = null;
        try {
            jarURL = new URL("jar", "", jarURL + "!/");
            JarURLConnection uc = (JarURLConnection) jarURL.openConnection();
            Attributes attr = uc.getMainAttributes();

            p = attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;


        } catch (Exception error) {
            return null;
        }
        return p;
    }
   /**
    * Check plugin to be correct
    * @return
    */
   public boolean Check(String plugin_name){
      if(Exists(plugin_name)){
        return true;
      } else {return false;}


  
   }

    public void UnloadAllPlugins() {
        
    }
}
